//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.sending;

import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.swing.*;
import org.jpgolay.me.agency.Agency;
import org.jpgolay.me.customer.Customer;
import org.jpgolay.me.number.NextNumber;
import org.jpgolay.me.persistence.ObjectCRUD;
import org.jpgolay.me.sale.SalesPiece;
import org.jpgolay.me.util.Parameter;

// Referenced classes of package org.jpgolay.me.sending:
//            SendingPanel, SendingCmdPanel, Sending, SendingPrint
public class SendingController {

    private class MouseClickOrderId extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                actionOrderIdField();
            }
        }

        MouseClickOrderId() {
        }
    }

    private class MouseClickDeliveryForm extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                actionDeliveryFormField();
            }
        }

        MouseClickDeliveryForm() {
        }
    }

    public SendingController(SendingPanel sendingPanel, SendingCmdPanel sendingCmdPanel, Parameter param) {
        modify = false;
        write = false;
        this.sendingPanel = sendingPanel;
        this.sendingCmdPanel = sendingCmdPanel;
        this.param = param;
        desktop = param.getDesktop();
        crud = new ObjectCRUD();
        changes = new PropertyChangeSupport(this);
        initLaw();
        initSendingPanel();
        initSendingCmdPanel();
    }

    private void initLaw() {
        if (param.getAccessLaw().length() >= 27 && param.getAccessLaw().charAt(27) == '1') {
            write = true;
        }
    }

    private void initSendingPanel() {
        sendingPanel.cleanField(true);
        sendingPanel.getOrderIdJTextField().addMouseListener(new MouseClickOrderId());
        sendingPanel.getDeliveryFormJTextField().addMouseListener(new MouseClickDeliveryForm());
        sendingPanel.getWeightJTextField().addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (sendingPanel.getWeight() == null || sendingPanel.getWeight().equals("")) {
                    sendingCmdPanel.getSave().setEnabled(false);
                    sendingCmdPanel.getPrint().setEnabled(false);
                } else {
                    sendingCmdPanel.getSave().setEnabled(write);
                    sendingCmdPanel.getPrint().setEnabled(true);
                }
            }
        });
    }

    private void initSendingCmdPanel() {
        sendingCmdPanel.getSave().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (modify) {
                    actionSaveModifySending();
                } else {
                    actionSave();
                }
            }
        });
        sendingCmdPanel.getDelete().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (modify) {
                    actionDeleteSending();
                }
            }
        });
        sendingCmdPanel.getClear().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                sendingPanel.cleanField(true);
                sendingCmdPanel.getSave().setEnabled(false);
                sendingCmdPanel.getDelete().setEnabled(false);
                sendingCmdPanel.getPrint().setEnabled(false);
                modify = false;
            }
        });
        sendingCmdPanel.getPrint().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionPrintLabel();
            }
        });
        sendingCmdPanel.getSave().setEnabled(false);
        sendingCmdPanel.getDelete().setEnabled(false);
        sendingCmdPanel.getPrint().setEnabled(false);
    }

    private void actionSave() {
        if (verifyRequirements()) {
            Integer id = (Integer) crud.create(33, null);
            if (id != null) {
                sending = (Sending) crud.read(id, 33);
                sending.setAgencyId(new Integer(sendingPanel.getAgencyId()));
                if (sendingPanel.getParcelQuantity() != null) {
                    sending.setParcelQuantity(new BigDecimal(sendingPanel.getParcelQuantity()));
                }
                sending.setBoxGTIN(sendingPanel.getBoxGTIN());
                sending.setOrderId(sendingPanel.getOrderId());
                if (sendingPanel.getDeliveryAnticipatedDate() != null) {
                    sending.setDeliveryAnticipatedDate(sendingPanel.getDeliveryAnticipatedDate());
                }
                if (sendingPanel.getSendingDate() != null) {
                    sending.setSendingDate(sendingPanel.getSendingDate());
                }
                if (sendingPanel.getPreparationDate() != null) {
                    sending.setPreparationDate(sendingPanel.getPreparationDate());
                }
                sending.setDeliveryForm(sendingPanel.getDeliveryForm());
                if (sendingPanel.getInsuranceValue() != null) {
                    sending.setInsuranceValue(new BigDecimal(sendingPanel.getInsuranceValue()));
                }
                sending.setWeight(new BigDecimal(sendingPanel.getWeight()));
                sending.setInsuranceCompany(sendingPanel.getInsuranceCompany());
                sending.setNotes(sendingPanel.getNotes());
                sending.setPackaging(new BigDecimal(sendingPanel.getPackaging()));
                sending.setPalletGTIN(sendingPanel.getPalletGTIN());
                sending.setSscc(sendingPanel.getSSCC());
                sending.setStatus(new Integer(sendingPanel.getStatus()));
                sending.setCustomerGLN(sendingPanel.getCustomerGLN());
                sending.setCustomerId(sendingPanel.getCustomerID());
                sending.setTruckingCompagny(sendingPanel.getTruckingCompany());
                sending.setUnit(sendingPanel.getUnit());
                sending.setUserId(param.getUserId());
                crud.update(sending, 33);
                sendingPanel.cleanField(false);
                sendingCmdPanel.getSave().setEnabled(false);
                sendingCmdPanel.getPrint().setEnabled(false);
                salesPiece.setSendingId(new BigDecimal(sending.getId().intValue()));
                changes.firePropertyChange("updateSalesPiece", "old", "updateSalesPiece");
            }
        }
    }

    private void actionPrintLabel() {
        String result = JOptionPane.showInputDialog(null, "Combien d'\351tiquettes souhaitez vous imprimer ?", "1");
        BigInteger quantity = null;
        try {
            quantity = new BigInteger(result);
        } catch (NumberFormatException e) {
            quantity = new BigInteger("1");
        }
        SendingPrint print = null;
        for (int i = 0; i < quantity.intValue(); i++) {
            print = new SendingPrint(sending, false, param);
            print = null;
        }

    }

    private boolean verifyRequirements() {
        if (sendingPanel.getOrderId() == null) {
            JOptionPane.showMessageDialog(null, "R\351f\351rence du BL invalide !");
            return false;
        }
        if (sendingPanel.getWeight() == null) {
            JOptionPane.showMessageDialog(null, "Poids invalide !");
            return false;
        }
        try {
            new BigDecimal(sendingPanel.getWeight());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Poids invalide ! \n(valeur num\351rique uniquement)");
            return false;
        }
        try {
            if (sendingPanel.getInsuranceValue() != null) {
                new BigDecimal(sendingPanel.getInsuranceValue());
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Valeur assur\351e invalide ! \n(valeur num\351rique uniquement)");
            return false;
        }
        try {
            if (sendingPanel.getParcelQuantity() != null) {
                new BigDecimal(sendingPanel.getParcelQuantity());
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Nb de colis invalide ! \n(valeure num\351rique (enti\350re) uniquement)");
            return false;
        }
        return true;
    }

    private void actionOrderIdField() {
        changes.firePropertyChange("orderIdField", "old", "orderIdField");
    }

    private void actionDeliveryFormField() {
        if (nextNumber == null) {
            nextNumber = new NextNumber();
        }
        if (sendingCmdPanel.getSave().isEnabled()) {
            sendingPanel.setDeliveryForm(nextNumber.getSendingNumber());
        }
    }

    private void actionSalesPieceSetPanel() {
        if (salesPiece.getSendingId().compareTo(new BigDecimal(0)) == 0) {
            sendingPanel.setOrderId(salesPiece.getId());
            sendingPanel.setInsuranceValue(salesPiece.getGrossPrice().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue()).toString());
        } else {
            JOptionPane.showMessageDialog(null, "Exp\351dition refus\351e !\nCe BL \340 d\351j\340 \351t\351 exp\351dier.");
            sendingPanel.cleanField(false);
            sendingCmdPanel.getSave().setEnabled(false);
            sendingCmdPanel.getPrint().setEnabled(false);
        }
    }

    private void actionCustomerSetPanel() {
        sendingPanel.setCustomerID(customer.getId());
        sendingPanel.setCustomerGLN(customer.getIdGLN());
    }

    private void actionAgencySetPanel() {
        sendingPanel.setAgencyId(agency.getId().intValue());
    }

    private void actionRead(Integer id) {
        modify = true;
        sending = (Sending) crud.read(id, 33);
        if (sending != null) {
            actionLoad();
        }
    }

    private void actionLoad() {
        sendingPanel.setAgencyId(sending.getAgencyId().intValue());
        sendingPanel.setParcelQuantity(sending.getParcelQuantity().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue()).toString());
        sendingPanel.setBoxGTIN(sending.getBoxGTIN());
        sendingPanel.setOrderId(sending.getOrderId());
        sendingPanel.setDeliveryAnticipatedDate(sending.getDeliveryAnticipatedDate());
        sendingPanel.setSendingDate(sending.getSendingDate());
        sendingPanel.setPreparationDate(sending.getPreparationDate());
        sendingPanel.setDeliveryForm(sending.getDeliveryForm());
        sendingPanel.setInsuranceValue(sending.getInsuranceValue().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue()).toString());
        sendingPanel.setWeight(sending.getWeight().setScale(param.getMinimumDecimalNumber().intValue(), param.getRoundType().intValue()).toString());
        sendingPanel.setInsuranceCompany(sending.getInsuranceCompany());
        sendingPanel.setNotes(sending.getNotes());
        sendingPanel.setPackaging(sending.getPackaging().setScale(0).toString());
        sendingPanel.setPalletGTIN(sending.getPalletGTIN());
        sendingPanel.setSSCC(sending.getSscc());
        sendingPanel.setStatus(sending.getStatus().intValue());
        sendingPanel.setCustomerGLN(sending.getCustomerGLN());
        sendingPanel.setCustomerID(sending.getCustomerId());
        sendingPanel.setTruckingCompany(sending.getTruckingCompagny());
        sendingPanel.setUnit(sending.getUnit());
        sendingPanel.setLastUpdateUser(sending.getUserId());
        sendingPanel.setLastUpdateTime(sending.getUpdateLastTime());
        sendingPanel.setId(sending.getId().toString());
        sendingPanel.setDeliveryDate(sending.getDeliveryDate());
        sendingCmdPanel.getSave().setEnabled(write);
        sendingCmdPanel.getDelete().setEnabled(write);
        sendingCmdPanel.getPrint().setEnabled(true);
    }

    private void actionDeleteSending() {
        int reponse = JOptionPane.showConfirmDialog(null, "Etes-vous certain de vouloir suprimer cette exp\351dition ?", "Confirmation", 1, 2, null);
        switch (reponse) {
            case 0: // '\0'
                crud.delete(sending.getId(), sending.getUpdateLastTime(), 33);
                SalesPiece salesPiece = (SalesPiece) crud.read(sending.getOrderId(), 22);
                if (salesPiece != null) {
                    salesPiece.setSendingId(new BigDecimal(0));
                    salesPiece.setDeliveryDate("");
                    crud.update(salesPiece, 22);
                }
                sendingPanel.cleanField(true);
                sendingCmdPanel.getSave().setEnabled(false);
                sendingCmdPanel.getDelete().setEnabled(false);
                sendingCmdPanel.getPrint().setEnabled(false);
                modify = false;
            // fall through

            case -1:
            case 1: // '\001'
            case 2: // '\002'
            default:
                return;
        }
    }

    private void actionSaveModifySending() {
        if (verifyRequirements()) {
            sending.setAgencyId(new Integer(sendingPanel.getAgencyId()));
            if (sendingPanel.getParcelQuantity() != null) {
                sending.setParcelQuantity(new BigDecimal(sendingPanel.getParcelQuantity()));
            }
            sending.setBoxGTIN(sendingPanel.getBoxGTIN());
            sending.setOrderId(sendingPanel.getOrderId());
            if (sendingPanel.getDeliveryAnticipatedDate() != null) {
                sending.setDeliveryAnticipatedDate(sendingPanel.getDeliveryAnticipatedDate());
            }
            if (sendingPanel.getSendingDate() != null) {
                sending.setSendingDate(sendingPanel.getSendingDate());
            }
            if (sendingPanel.getPreparationDate() != null) {
                sending.setPreparationDate(sendingPanel.getPreparationDate());
            }
            sending.setDeliveryForm(sendingPanel.getDeliveryForm());
            if (sendingPanel.getInsuranceValue() != null) {
                sending.setInsuranceValue(new BigDecimal(sendingPanel.getInsuranceValue()));
            }
            sending.setWeight(new BigDecimal(sendingPanel.getWeight()));
            sending.setInsuranceCompany(sendingPanel.getInsuranceCompany());
            sending.setNotes(sendingPanel.getNotes());
            sending.setPackaging(new BigDecimal(sendingPanel.getPackaging()));
            sending.setPalletGTIN(sendingPanel.getPalletGTIN());
            sending.setSscc(sendingPanel.getSSCC());
            sending.setStatus(new Integer(sendingPanel.getStatus()));
            sending.setCustomerGLN(sendingPanel.getCustomerGLN());
            sending.setCustomerId(sendingPanel.getCustomerID());
            sending.setTruckingCompagny(sendingPanel.getTruckingCompany());
            sending.setUnit(sendingPanel.getUnit());
            sending.setUserId(param.getUserId());
            crud.update(sending, 33);
            sendingPanel.cleanField(true);
            sendingCmdPanel.getSave().setEnabled(false);
            sendingCmdPanel.getDelete().setEnabled(false);
            sendingCmdPanel.getPrint().setEnabled(false);
            modify = false;
        }
    }

    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }

    public String getPieceId() {
        return salesPiece.getId();
    }

    public Agency getAgency() {
        return agency;
    }

    public void setAgency(Agency agency) {
        this.agency = agency;
        actionAgencySetPanel();
    }

    public SalesPiece getSalesPiece() {
        return salesPiece;
    }

    public void setSalesPiece(SalesPiece salesPiece) {
        this.salesPiece = salesPiece;
        actionSalesPieceSetPanel();
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
        actionCustomerSetPanel();
    }

    public void modifySending(String sendingId) {
        actionRead(new Integer(sendingId));
    }
    private SendingPanel sendingPanel;
    private SendingCmdPanel sendingCmdPanel;
    private Parameter param;
    private JDesktopPane desktop;
    private ObjectCRUD crud;
    private boolean checkOrder;
    private PropertyChangeSupport changes;
    private Agency agency;
    private SalesPiece salesPiece;
    private Customer customer;
    private NextNumber nextNumber;
    private boolean modify;
    private Sending sending;
    private boolean write;
}
